package org.dreamwork.cai.monitor.web;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet (urlPatterns = "/backend/server-info")
public class BackendServlet extends HttpServlet {
    @Override
    protected void doGet (HttpServletRequest req, HttpServletResponse resp) throws IOException {
        // 必须先获取一次session，否则后面的websocket无法获取session
        req.getSession ();
        resp.setContentType ("application/json;charset=utf-8");
/*
        StringBuffer uri = req.getRequestURL ();
        String path = req.getServletPath ();
        System.out.println ("uri  = " + uri);
        System.out.println ("path = " + path);
        System.out.println ("info = " + req.getPathInfo ());
        System.out.println ("server info = " + req.getServerName () + ":" + req.getLocalPort () + req
        .getContextPath ());
*/

        String schema = "ws://";
        String server = req.getServerName ();
        String s_port = "";
        int port = req.getServerPort ();
        if (port == 443) {
            schema = "wss://";
        } else if (port != 80) {
            s_port = ":" + port;
        }
        String path = schema + server + s_port + req.getContextPath ();

        resp.getWriter ().write ("{\"context-path\":\"" + path + "\"}");
    }
}